// src-tauri/src/multi_level_trust.rs
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

use crate::trust_chain::PeerRole;

#[derive(Serialize, Deserialize, Clone)]
pub struct MultiLevelCertificate {
    pub peer_id: String,
    pub public_key: String,
    pub role: PeerRole,
    pub trust_level: u8, // 0=God, 1=一级Trusted Peer, 2=二级, 等等
    pub issued_by: String, // 签发者peer_id
    pub issue_date: u64,
    pub expiry_date: u64,
    pub signature: String,
    pub max_subordinates: u8, // 最多可授权的下级数量
    pub current_subordinates: u8, // 当前已授权的下级数量
    pub parent_peer_id: Option<String>, // 父节点peer_id
}

#[derive(Serialize, Deserialize, Clone)]
pub struct TrustChainTree {
    root_peer_id: String,
    certificates: HashMap<String, MultiLevelCertificate>,
    children_map: HashMap<String, Vec<String>>, // parent_peer_id -> children_peer_ids
    max_depth: u8,
    max_children_per_node: u8,
}

impl TrustChainTree {
    pub fn new(god_peer_id: String, god_public_key: String, max_depth: u8, max_children: u8) -> Self {
        let god_certificate = MultiLevelCertificate {
            peer_id: god_peer_id.clone(),
            public_key: god_public_key,
            role: PeerRole::God,
            trust_level: 0,
            issued_by: god_peer_id.clone(),
            issue_date: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(),
            expiry_date: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs() + 365 * 24 * 60 * 60,
            signature: "self_signed".to_string(),
            max_subordinates: max_children,
            current_subordinates: 0,
            parent_peer_id: None,
        };

        let mut certificates = HashMap::new();
        certificates.insert(god_peer_id.clone(), god_certificate);

        let mut children_map = HashMap::new();
        children_map.insert(god_peer_id.clone(), Vec::new());

        Self {
            root_peer_id: god_peer_id,
            certificates,
            children_map,
            max_depth,
            max_children_per_node: max_children,
        }
    }

    pub fn authorize_subordinate(
        &mut self,
        issuer_peer_id: String,
        applicant_peer_id: String,
        applicant_public_key: String,
        issuer_private_key: &[u8],
    ) -> Result<MultiLevelCertificate, String> {
        // 验证签发者权限
        let issuer_cert = self.certificates.get(&issuer_peer_id)
            .ok_or("Issuer not found")?;

        if issuer_cert.trust_level >= self.max_depth {
            return Err("Cannot authorize subordinates at maximum depth".to_string());
        }

        if issuer_cert.current_subordinates >= issuer_cert.max_subordinates {
            return Err("Issuer has reached maximum subordinate limit".to_string());
        }

        // 计算新节点的信任级别
        let new_trust_level = issuer_cert.trust_level + 1;

        let new_certificate = MultiLevelCertificate {
            peer_id: applicant_peer_id.clone(),
            public_key: applicant_public_key,
            role: PeerRole::Trusted,
            trust_level: new_trust_level,
            issued_by: issuer_peer_id.clone(),
            issue_date: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(),
            expiry_date: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs() + 180 * 24 * 60 * 60, // 6个月
            signature: self.sign_certificate(&applicant_peer_id, issuer_private_key)?,
            max_subordinates: self.max_children_per_node,
            current_subordinates: 0,
            parent_peer_id: Some(issuer_peer_id.clone()),
        };

        // 更新数据结构
        self.certificates.insert(applicant_peer_id.clone(), new_certificate.clone());
        
        // 更新子节点映射
        self.children_map.entry(issuer_peer_id.clone())
            .or_insert_with(Vec::new)
            .push(applicant_peer_id.clone());
        self.children_map.insert(applicant_peer_id.clone(), Vec::new());

        // 更新签发者的下属计数
        if let Some(issuer_cert) = self.certificates.get_mut(&issuer_peer_id) {
            issuer_cert.current_subordinates += 1;
        }

        Ok(new_certificate)
    }

    pub fn get_trusted_peers_at_level(&self, level: u8) -> Vec<MultiLevelCertificate> {
        self.certificates.values()
            .filter(|cert| cert.trust_level == level)
            .cloned()
            .collect()
    }

    pub fn get_descendants(&self, peer_id: &str) -> Vec<MultiLevelCertificate> {
        let mut descendants = Vec::new();
        self.collect_descendants(peer_id, &mut descendants);
        descendants
    }

    fn collect_descendants(&self, peer_id: &str, descendants: &mut Vec<MultiLevelCertificate>) {
        if let Some(children) = self.children_map.get(peer_id) {
            for child_id in children {
                if let Some(child_cert) = self.certificates.get(child_id) {
                    descendants.push(child_cert.clone());
                    self.collect_descendants(child_id, descendants);
                }
            }
        }
    }

    pub fn get_ancestry_path(&self, peer_id: &str) -> Result<Vec<MultiLevelCertificate>, String> {
        let mut path = Vec::new();
        let mut current_id = peer_id;

        while let Some(cert) = self.certificates.get(current_id) {
            path.push(cert.clone());
            
            match &cert.parent_peer_id {
                Some(parent_id) => current_id = parent_id,
                None => break, // 到达根节点
            }
        }

        path.reverse(); // 从根节点到当前节点
        Ok(path)
    }

    pub fn calculate_trust_weight(&self, peer_id: &str) -> f64 {
        // 基于层级计算信任权重，层级越高权重越低
        match self.certificates.get(peer_id) {
            Some(cert) => {
                let level_factor = 1.0 / (2.0f64).powi(cert.trust_level as i32);
                let activity_factor = self.calculate_activity_factor(peer_id);
                level_factor * activity_factor
            }
            None => 0.0,
        }
    }

    pub fn can_authorize_subordinate(&self, peer_id: &str) -> bool {
        self.certificates.get(peer_id)
            .map(|cert| {
                cert.trust_level < self.max_depth && 
                cert.current_subordinates < cert.max_subordinates
            })
            .unwrap_or(false)
    }
}